package com.ganyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ganyu.domain.LoginUser;
import com.ganyu.domain.entity.User;
import com.ganyu.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.ganyu.constant.SystemConstant.ADMIN;

/**
 * DATA: 2022/9/15
 * Author: 晨夕
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //1.在数据库中根据姓名返回用户信息，并封装为新对象
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUserName,s);
        User user = userMapper.selectOne(query);
        //2.判断获取的用是否为空
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        //封装用户权限，必须是后台用户
        if(user.getType().equals(ADMIN)){
            //1. 先根据user_id获取role_id
            Long roleId = userRoleMapper.getRoleId(user.getId());
            //2. 根据role_id获取menu_id
            List<Long> menuId = roleMenuMapper.getMenuId(roleId);
            ArrayList<String> perms = new ArrayList<>();
            //3. 根据menu_id获取perms
            for(Long id : menuId){
                String perById = menuMapper.getPerById(id);
                perms.add(perById);
            }
            return new LoginUser(user,perms);
        }
        return new LoginUser(user,null);
    }
}
